package com.wanwu.channel.common.util;

import com.wanwu.channel.common.enums.ExceptionEnum;
import com.wanwu.channel.common.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;

/**
 * @author runquanchen
 * @version 1.0
 * @date 2020-03-09 11:49
 * @project channel
 */
public  class GetSerialNoUtils {
    private static final Logger logger = LoggerFactory.getLogger(GetSerialNoUtils.class);
    private static final String sep = "\\.";

    private static String ipKey;

    private static String getIpkey() {

        if (StringUtils.isNotBlank(ipKey) && ipKey.length()==6) {
            return ipKey;
        } else {
            try {
                LogUtil.info(logger, "初始化获取本机ip的序列值");
                //获取ip后两个地址位生成6位的序列值
                String ip = InetAddress.getLocalHost().getHostAddress();
                if (StringUtils.isNotBlank(ip) && ip.split(sep).length > 3) {
                    ipKey = (Integer.valueOf(ip.split(sep)[2]) + 100) + "" + (Integer.valueOf(ip.split(sep)[3]) + 100);
                    if (ipKey.length() != 6) {
                        ipKey = RandomUtil.randomNStr(6);
                    }
                } else {
                    ipKey = RandomUtil.randomNStr(6);
                }
            } catch (Exception e) {
                LogUtil.error(logger, e, "初始化获取本机ip的序列值，使用随机数");
                ipKey = RandomUtil.randomNStr(6);
            }
            return ipKey;
        }
    }

    /**
     * 生成渠道单号
     *
     * @param
     * @return
     */
    public static String getChannelNo(String flag) {
        if (flag == null) {
            throw new SystemException(ExceptionEnum.E10030);
        }
        //时间戳+ip序列+随机值，总共27位+flag位
        return flag + System.currentTimeMillis() + getIpkey() + RandomUtil.randomNStr(8);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10000 ; i++) {
            System.out.println(getChannelNo("1"));

        }
    }
}
